package cn.benma666.sjsj.job;

import cn.benma666.exception.MyException;
import cn.benma666.iframe.MyParams;
import cn.benma666.sjsj.znjh.BasicClq;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 流程处理
 */
@Component
@XxlJob(value = "LcclHandler",init = "init")
public class LcclJob extends BasicJob{
    /**
     * spring容器，可以从中获取注册的bean
     */
    private static ApplicationContext context;
    private JSONObject clqMap;
    private JSONObject jcxx;

    public LcclJob(ApplicationContext context) {
        LcclJob.context = context;
    }
    /**
     * 任务体
     */
    public void execute() throws Exception {
        info("开始数据同步");
        jcxx = getConfig().getJSONObject("jcxx");
        clqMap = getConfig().getJSONObject("clq");
        clqzx( null, jcxx.getJSONArray("startClq"));
        info("结束数据同步");
    }

    /**
     * 处理器执行
     * @param list 数据列表
     * @param clqArr 处理器数组
     */
    private void clqzx(List<JSONObject> list, JSONArray clqArr) {
        for(Object clqKey: clqArr.toArray(new Object[0])){
            MyParams clq = new MyParams(clqMap.getJSONObject(clqKey.toString()));
            JSONArray xygClq;
            try {
                BasicClq clqBean = (BasicClq) context.getBean(clq.getString("$.znjh.clq"));
                list = clqBean.plcl(clq, list,this);
                xygClq = valByDef(clq.getJSONArray("$.znjh.ljq.success"), clq.getJSONArray("$.znjh.ljq.default"));
                if(isBlank(xygClq)){
                    //正常结束
                    return;
                }
            }catch (Exception e){
                xygClq = valByDef(clq.getJSONArray("$.znjh.ljq.failed"), clq.getJSONArray("$.znjh.ljq.default"));
                if(isBlank(xygClq)){
                    //失败且没有配置对应处理器
                    throw new MyException("执行失败",e);
                }
            }
            clqzx(list,xygClq);
        }
    }
}
